package com.apexsoft.assets.base.request;


import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @Description: 功能码请求规范
 * @author: Logan
 * @date: 2020-10-09 08:54
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Slf4j
@ApiModel
public class ARequest extends QueryJSONRequest {
    private String sessionId;
    private String serviceId;
    private Map<String,Object> head = new HashMap<>();
    private Map<String,Object> data = new HashMap<>();

    public void addAllHead(Map<String,Object> head){
        this.head.putAll(head);
    }
    public void setHead(Map<String,Object> head) {
        this.head.putAll(head);
    }
    public <T> T getData(String paramKey, Class<T> clazz){
        Object o = this.data.get(paramKey);
        if(Objects.nonNull(o)) {
            if(clazz.isInstance(o)) {
                return (T)o;
            } else {
                if(o instanceof Number) {
                    String str = String.valueOf(o);
                    if(clazz == Double.class) {
                        return (T)Double.valueOf(str);
                    } else if(clazz == Float.class) {
                        return (T)Float.valueOf(str);
                    } else if(clazz == Integer.class) {
                        return (T)Integer.valueOf(str);
                    } else if(clazz == Long.class) {
                        return (T)Long.valueOf(str);
                    } else {
                        throw new RuntimeException("类型无法转化");
                    }
                }
            }

        }
        return null;
    }
    public <T> T getData(String paramKey, Class<T> clazz, T defaultValue){
        T result = getData(paramKey, clazz);
        if(result == null){
            result=defaultValue;
        }
        return result;
    }

    public <T> T getData( Class<T> clazz){
        try {
            T t = clazz.newInstance();
            BeanUtils.populate( t, data);
            return t;
        } catch (IllegalAccessException e) {
            log.error("对象转化异常", e);
            throw new RuntimeException("对象转化异常", e);
        } catch (InstantiationException e) {
            log.error("对象转化异常", e);
            throw new RuntimeException("对象转化异常", e);
        } catch (InvocationTargetException e) {
            log.error("对象转化异常", e);
            throw new RuntimeException("对象转化异常", e);
        }
    }
    public void setData(Map<String,Object> data) {
        this.data.putAll(data);
    }
    public void setData(String paramKey,Object paramValue){
        this.data.put(paramKey,paramValue);
    }


}
